from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect as redirect
from django.contrib.auth import authenticate
from StartGroup.models import Group
from groupMembers.models import Member_Group
from contifyuser.models import Member
from django.contrib.auth.models import User
from discussions.forms import StartNewDiscussionForm
from discussions.forms import PostNewCommentForm
from discussions.models import Discussion
from discussions.models import Disc_Comment
import connectpeople.Constants
import Constants
import datetime
from django.db.models import Count
import simplejson
from django.http import HttpResponse
from django.core.paginator import Paginator
from time import strftime
from django.utils.safestring import mark_safe
from datetime import datetime
import utils.signals

# render form for creating a new discussion/ posting new comment
def discussionCommentForm(request):
    
    # Create New Discussion form initialization
    create_new_discussion_form = StartNewDiscussionForm()
        
    return render_to_response(Constants.discussions + Constants.post_disc_comment_template,
                              {Constants.create_new_discussion_form_constant: create_new_discussion_form},
                              context_instance = RequestContext(request))
    
# render post discussion confirmation
def postDiscussion(request):
    
    if connectpeople.Constants.session_group_web_address in request.session:
        group_web_addr = request.session[connectpeople.Constants.session_group_web_address]
        userid = request.session[connectpeople.Constants.session_userid]
        group = getGroupInfo(group_web_addr)
        user = getUserInfo(userid)
        member = getMemberInfo(user)
        
        if request.method == 'POST':
            # Create New Event form initialization
            create_new_discussion_form = StartNewDiscussionForm(data=request.POST)
            if create_new_discussion_form.is_valid():
                create_new_discussion_form.save(group, member.first_name, member.photo)
                
                # Get user ids of all users associated with the group
                grp_mem_usrid = getGroupMembersUserIds(group)
                # Get email ids of these users
                recipient_list = User.objects.filter(username__in=grp_mem_usrid).values_list('email', flat=True)
                # Compose subject for the email
                subj = group.group_name + " - New Discussion Posted"
                # Send Email alerts
                utils.signals.send_mail.send(
                   sender=Discussion, email=recipient_list, model=request.POST, subject=subj, template="email/NewDiscussionEmail.html")
                
                return redirect(Constants.discussion_portal_url)

    return redirect(Constants.post_discussion_form_url)


# render discussion portal
def discussionPortal(request):
    
    group_discussion_list = []
    if connectpeople.Constants.session_group_web_address in request.session:
        group_web_addr = request.session[connectpeople.Constants.session_group_web_address]
        group = getGroupInfo(group_web_addr)
   
    
    # Ajax call is made to delete the discussion    
    if request.method == 'POST':
        # Get the discussion id to be deleted
        discid = request.POST.__getitem__('discid')
        # Delete the discussion. Note this will also delete all the
        # instances of this duscusssion where Discussion is Foreign Key
        Discussion.objects.get(id=discid).delete()
        # Get Discussions list
        discussions = getDiscussions(group)        
        group_discussion_list = geDiscussionsList(discussions)
        # Get Html for discussion table
        dataHtml = discPortalData(group_discussion_list)
        # Set response to html value of the discussion table
        response = simplejson.dumps({'dataHtml':dataHtml})
    else:
        # Get Discussions list
        discussions = getDiscussions(group)        
        group_discussion_list = geDiscussionsList(discussions)
        # Get Html for discussion table
        dataHtml = discPortalData(group_discussion_list)

    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
        
    return render_to_response(Constants.discussions + Constants.discussion_portal_template,
                              {Constants.group_discussion_list_constant: group_discussion_list,
                               'dataHtml': dataHtml},
                              context_instance = RequestContext(request))

# render discussion view
def discussionView(request, id):
    
    discussion = Discussion.objects.get(id = id)
    userid = request.session[connectpeople.Constants.session_userid]
    user = getUserInfo(userid)
    member = getMemberInfo(user)
    group_web_addr = request.session[connectpeople.Constants.session_group_web_address]
    group = getGroupInfo(group_web_addr)

    # Save comment if posted
    if request.method == 'POST':
        # Get the comment id to be deleted
        try:
            commid = request.POST.__getitem__('commid')
        except:
            # If attribute not defined then request has come
            # to add new comment
            commid = None
            
        if commid:
            # Delete the comment from database
            Disc_Comment.objects.get(id=commid).delete()
            # Set response to success
            response = simplejson.dumps({'success':'success'})
        else:
            # Create New Event form initialization
            post_new_comment_form = PostNewCommentForm(data=request.POST)
            if post_new_comment_form.is_valid():           

                # Save the form
                post_new_comment_form.save(discussion, member.first_name, member.photo)
                # Update last updated values
                updateDiscussionLastUpdate(discussion, member.first_name)
                
                # Get user ids of all users associated with the group
                grp_mem_usrid = getGroupMembersUserIds(group)
                # Get email ids of these users
                recipient_list = User.objects.filter(username__in=grp_mem_usrid).values_list('email', flat=True)
                # Compose subject for the email
                subj = discussion.topic + " discussion - New Comment Posted"
                # Send Email alerts
                utils.signals.send_mail.send(
                   sender=Discussion, email=recipient_list, model=member.first_name, subject=subj, template="email/newCommentEmail.html")
                
                # Recent comment info
                rec_post_dt = datetime.now().strftime('%Y, %b, %d')
                rec_comment = request.POST
                recentPost = {'rpd': rec_post_dt, 'rc': rec_comment}
                # Set response to same input comment value
                response = simplejson.dumps(recentPost)
            

    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
  
    # Post New Comment form initialization
    post_new_comment_form = PostNewCommentForm()
    
    comments = getComments(discussion)
    comments_list = geCommentsList(comments)
    paginator = Paginator(comments_list, 10)

    
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        pages = paginator.page(page)
    except (EmptyPage, InvalidPage):
        pages = paginator.page(paginator.num_pages)

    
    return render_to_response(Constants.discussions + Constants.discussion_view_template,
                              {'discussion': discussion, Constants.post_new_comment_form_constant: post_new_comment_form,
                               'pages': pages, 'curr_member': member},
                              context_instance = RequestContext(request))
    

# Helper function to obtain user info from User model
def getUserInfo(userid):
    return User.objects.get(username=userid)

# Helper function to obtain Group related to a group_web_address
def getGroupInfo(group_web_addr):
    return Group.objects.get(group_web_address= group_web_addr)
    
# Helper function to obtain Discussions related to the group
def getDiscussions(group_info):
    return Discussion.objects.filter(group = group_info).order_by('-last_update_dt')

# Helper function to obtain Comments related to the Discussion
def getComments(disc_info):
    return Disc_Comment.objects.filter(discussion = disc_info).order_by('post_date')

# Helper function to obtain member info from Member model
def getMemberInfo(user_info):
    return Member.objects.get(user=user_info)

# Helper function to obtain Discussions in a list format
def geDiscussionsList(group_discs):
    num_posts = 0
    group_discussion_list = []
    if group_discs is not None:
        for each in group_discs:
            q = Disc_Comment.objects.filter(discussion=each).annotate(num_posts=Count('comment'))
            num_posts = q.count()
            group_discussion_list.append((each, num_posts))
    
    return group_discussion_list


# Helper function to obtain Comments in a list format
def geCommentsList(disc_comments):
    num_posts = 0
    disc_comments_list = []
    if disc_comments is not None:
        for each in disc_comments:
            disc_comments_list.append(each)
    
    return disc_comments_list

# Helper function to update the Last Update date and
# Last post by fields on Discussion model
def updateDiscussionLastUpdate(discussion, memberName):
    discussion.last_update_dt = datetime.now()
    discussion.last_post_by = memberName
    discussion.save()
    
# build discussion data table
def discPortalData(group_discussion_list):
    dataHtml= []
    if group_discussion_list:
        for discussion, count in group_discussion_list:
            # Discussion Topic
            dataHtml.append("<div class='nobreak discPorTableTopicHeader'><a href='../../connectpeople/discussions/")
            dataHtml.append(str(discussion.id))
            dataHtml.append("'>")
            dataHtml.append(discussion.topic)
            dataHtml.append("</a></div>")
            # Discussion Comment - Last Post By
            dataHtml.append("<div class='nobreak discPorTableAuthorHeader'>")
            dataHtml.append(discussion.last_post_by)
            dataHtml.append("</div>")
            # Number of comment posts
            dataHtml.append("<div class='nobreak discPorTablePostsHeader'>")
            dataHtml.append(str(count))
            dataHtml.append("</div>")
            # Last Updated Date
            dataHtml.append("<div class='nobreak discPorTableLastPostHeader'>")
            dataHtml.append(str(datetime.date(discussion.last_update_dt)))
            dataHtml.append("</div>")
            # Delete button
            dataHtml.append("<div class='discPorTableDeleteButton'><button id='delete")
            dataHtml.append(str(discussion.id))
            dataHtml.append("' class='delButton' discid='")
            dataHtml.append(str(discussion.id))
            dataHtml.append("' type='button'>Delete</button></div>")
    
    return mark_safe(u''.join(dataHtml))
    
# Get All the members associated with the group
def getGroupMembersUserIds(group):
    return Member_Group.objects.filter(group = group).values_list('user_id', flat=True)